// WynnREADME : 尽量不要用save，用create或者update， 主要是为了做重复性检查；
module.exports = function(lab) {
    return {

        /**
         * @apiDefine TypeDefineBrand
         * @apiSuccess (BrandSKU) {String} id 产品Id
         * @apiSuccess (BrandSKU) {String} ouid 用户Id
         * @apiSuccess (BrandSKU) {String} barcode 商品条形码
         * @apiSuccess (BrandSKU) {String} item_code 商品编码
         * @apiSuccess (BrandSKU) {String} brand 品牌
         * @apiSuccess (BrandSKU) {String} category 品类
         * @apiSuccess (BrandSKU) {String} image_url 图片路径
         * @apiSuccess (BrandSKU) {Number} name 名称
         * @apiSuccess (BrandSKU) {Number} list_price 建议零售价
         * @apiSuccess (BrandSKU) {Number} market_price 原价
         * @apiSuccess (BrandSKU) {String} retail_unit 零售单位
         * @apiSuccess (BrandSKU) {String} memo 备注
         */

        // 导入sku查询逻辑 ： 商品条形码是否存在
        // 商品条形码存在   判断商品编码是否存在
        // 商品编码存在 再判断零售单位 存在 根据 商品条形码、商品编码、零售单位三者查询  不存在 根据商品条形码、商品编码查询
        // 商品编码不存在 再判断零售单位 存在 根据商品条形码、零售单位查询 不存在 根据商品条形码查询
        // 商品条形码不存在 零售单位是否存在 存在 根据商品编码、零售单位查询  不存在 根据商品编码查询
        @findSKU: function(ouid, { barcode, item_code, retail_unit }) {

            let query;

            if (item_code) {


                if (retail_unit) {
                    query = ["item_code == ? && retail_unit == ? && ouid == ?", item_code, retail_unit, ouid];
                } else {
                    query = ["item_code == ? && ouid == ?", item_code, ouid];
                }


            } else {

                if (retail_unit) {
                    query = ["barcode == ? && retail_unit == ? && ouid == ?", barcode, retail_unit, ouid];
                } else {
                    query = ["barcode == ? && retail_unit == null && ouid == ?", barcode, ouid];
                }

            }
            return lab.find("slime_brand_skus", { "!": query })

        },
        @importSKU: function(ouid, { barcode, item_code, retail_unit, name, brand, category, list_price, market_price, image_url, memo, on_sale = false, tags, spec, weight }) {

            return lab.snapshot(function(snapshot) {

                barcode = barcode ? (barcode + "") : null;
                item_code = item_code ? (item_code + "") : null;

                return snapshot.slime.brand.@findSKU(ouid, { barcode, item_code, retail_unit }).then(function(result) {

                    let existingSKU;
                    let newBrandSKU;

                    if (result) {
                        existingSKU = result;
                    } else {
                        existingSKU = {
                            "id": @.uuid(),
                            "ouid": ouid,
                            "item_code": item_code ? item_code : undefined,
                            "barcode": barcode ? barcode : undefined,
                            "retail_unit": retail_unit ? retail_unit : undefined,
                            "create_date": Date.now()
                        }
                        newBrandSKU = true;
                    }

                    var skuData = {};

                    if (!name && newBrandSKU) {
                        throw @lab.errors.invalid_parameters
                    }

                    skuData["name"] = name;

                    if (existingSKU) {
                        skuData["barcode"] = barcode || existingSKU.barcode;
                    }

                    skuData["category"] = category;
                    skuData["brand"] = brand;

                    skuData["list_price"] = list_price ? Math.round(parseFloat(list_price) * 100) : undefined;
                    skuData["market_price"] = market_price ? Math.round(parseFloat(market_price) * 100) : undefined;

                    skuData["memo"] = memo;

                    skuData["last_update"] = Date.now();
                    skuData["is_removed"] = false;

                    skuData["image_url"] = image_url;

                    skuData["tags"] = tags
                    skuData["spec"] = spec
                    skuData["weight"] = weight || 0

                    // spec => spec price table;

                    if ((!existingSKU["on_sale"] && existingSKU["on_sale"] !== false) || on_sale) {
                        existingSKU["on_sale"] = on_sale
                    }

                    if (result) {
                        @.keys(skuData).forEach(function(key) {
                            if (skuData[key]) {
                                existingSKU[key] = skuData[key]
                            }
                        })
                        snapshot.updateWithoutCache("slime_brand_skus", existingSKU).pipe(this);
                    } else {
                        snapshot.create("slime_brand_skus", @.merge.simple(existingSKU, skuData)).pipe(this);
                    }

                })
            }).then(function(sku) {

                @mew.auto("slime.brand.updateSKU", sku)

                this.next(sku)
            })

        },
        @getSKUByID: function(currentOU, id) {
            return lab.find("slime_brand_skus", {
                id: id,
                ouid: currentOU.id,
            });
        },
        getSKUByIDs: function(session, ids = []) {
            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }
            if (!ids || ids.length == 0) {
                return @.async.resolve([])
            } else {
                return lab.sqlite.find("slime_brand_skus", {
                    id: ["in", ids],
                    ouid: session.currentOU.id,
                }).then(function({ records }) {
                    this.next(records);
                });
            }
        },
        getSKUByID: function(session, id) {
            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }
            return lab.slime.brand.@getSKUByID(session.currentOU, id)
        },
        getSKUByItemCode: function(session, item_code) {
            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }
            return lab.find("slime_brand_skus", {
                ouid: session.currentOU.id,
                item_code
            });
        },

        /**
         * @api {jsonrpc} slime@brand.searchSKUs(form)=result slime@brand.searchSKUs
         * @apiDescription 查询符合搜索条件的商品数据
         * @apiGroup slime
         * @apiParam (form) {Number} [start=0] 分页开始
         * @apiParam (form) {Number} [limit=10] 分页最大
         * @apiParam (form) {String} brand 品牌
         * @apiParam (form) {String} category 品类
         * @apiParam (form) {String} keyword 名称(name)或商品条形码(barcode)
         * @apiParam (form) {Number} price_low 价格范围中的低价格
         * @apiParam (form) {Number} price_high 价格范围中的高价格
         *
         * @apiSuccess (result) {Object} total 商品总数 list 商品列表
         * @apiSuccess (list[]) {String} id 商品ids
         * @apiSuccess (list[]) {String} brand 品牌
         * @apiSuccess (list[]) {String} category 品类
         * @apiSuccess (list[]) {String} barcode 商品条形码
         * @apiSuccess (list[]) {String} item_code 商品编码
         * @apiSuccess (list[]) {String} name 商品名称
         * @apiSuccess (list[]) {Number} list_price 零售价
         * @apiSuccess (list[]) {Number} market_price 原价
         * @apiSuccess (list[]) {Number} memo 备注
         */
        searchSKUs: function(session, { start, limit, id, store_id, brand, category, keyword, price_low, price_high, on_sale = true, sort = "last_update desc" }) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            var condition = ["a.is_removed = ?"];
            var params = [false];

            var models = ["slime_brand_skus as a"];
            var fields = [];

            condition.push("a.ouid = ?");
            params.push(session.currentOU.id);

            if (brand) {

                if (Array.isArray(brand)) {

                    if (brand.length) {
                        condition.push("a.brand in ('" + brand.join("','") + "')");
                    }

                } else {
                    condition.push("a.brand = ?");
                    params.push(brand);
                }

            }

            if (category) {
                if (Array.isArray(category)) {
                    if (category.length) {
                        condition.push("a.category in ('" + category.join("','") + "')");
                    }
                } else {
                    condition.push("a.category = ?");
                    params.push(category);
                }
            }

            if (id) {
                if (Array.isArray(id)) {
                    if (id.length) {
                        condition.push("a.id in ('" + id.join("','") + "')");
                    }
                } else {
                    condition.push("a.id = ?");
                    params.push(id);
                }
            }

            if (keyword) {
                condition.push("(a.name like ? or a.barcode like ? or a.item_code like ? or a.brand like ? or a.category like ?)");
                params.push("%" + keyword + "%", "%" + keyword + "%", "%" + keyword + "%", "%" + keyword + "%", "%" + keyword + "%");
            }

            // 在添加完slime_store_brand_skus这个之后，帮忙测试一下根据store_id搜索逻辑
            if (store_id) {

                models.push("left join slime_store_brand_skus as b on b.sku_id = a.id and b.store_id = ?");
                fields.push("a.*");
                fields.push("b.id as store_sku_id");
                fields.push("b.on_sale as store_on_sale");
                fields.push("b.list_price as store_list_price");


                params.unshift(store_id);

                if (price_low) {
                    condition.push("((b.list_price is null and a.list_price >= ?) or (b.list_price >= ?))");
                    params.push(Math.round(price_low * 100));
                    params.push(Math.round(price_low * 100));
                }

                if (price_high) {
                    condition.push("((b.list_price is null and a.list_price <= ?) or (b.list_price <= ?))");
                    params.push(Math.round(price_high * 100));
                    params.push(Math.round(price_high * 100));
                }

                //           : on_sale = true, 返回on_sale = true的， 
                //            on_sale = false, 返回

                if (on_sale) {
                    condition.push("((b.on_sale is null and a.on_sale = ?) or (b.on_sale = ?))");
                    params.push(true);
                    params.push(true);
                }

            } else {

                if (price_low) {
                    condition.push("a.list_price >= ?");
                    params.push(Math.round(price_low * 100));
                }

                if (price_high) {
                    condition.push("a.list_price <= ?");
                    params.push(Math.round(price_high * 100));
                }

                if (on_sale) {
                    condition.push("a.on_sale = ?");
                    params.push(true);
                }
            }


            return lab.query(models, {
                "fields": fields,
                "conditions": condition,
                "params": params,
                "start": start,
                "limit": limit,
                "sort": sort,
                "mapper": function(sku) {
                    if (sku.store_sku_id) {
                        sku.on_sale = sku.store_on_sale;
                        sku.list_price = sku.store_list_price;
                    }
                    sku.tags = JSON.parse(sku.tags);
                    sku.list_price = parseFloat(sku.list_price / 100.0);
                    sku.market_price = parseFloat(sku.market_price / 100.0);
                    sku.cost_price = parseFloat(sku.cost_price / 100.0);
                    return sku;
                }
            })
        },
        getSKUSearchParameters: function(session) {
            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }
            return lab.sqlite.query("select distinct(brand) as brand from slime_brand_skus where is_removed = ? and ouid = ?", false, session.currentOU.id).then(function({ records }) {

                this.pool.brands = records.map(function(record) {
                    return record.brand;
                });

                lab.sqlite.query("select distinct(category) as category from slime_brand_skus where is_removed = ? and ouid = ?", false, session.currentOU.id).pipe(this);

            }).then(function({ records }) {

                this.pool.categorys = records.map(function(record) {
                    return record.category;
                });

                lab.sqlite.query("select * from slime_brand_skus where is_removed = ? and ouid = ? limit 0,10", false, session.currentOU.id).pipe(this);


            }).then(function({ records }) {

                this.pool.skus = records;

                this.next({
                    "skus": this.pool.skus,
                    "brands": this.pool.brands,
                    "categories": this.pool.categorys
                });
            });
        },
        /**
         * @api {jsonrpc} slime@brand.batchDeleteSKUs()=result slime@brand.batchDeleteSKUs
         * @apiDescription 批量删除商品数据
         * @apiGroup slime
         * @apiSuccess {Object} changes 删除商品数据总数
         */
        // 批量删除
        batchDeleteSKUs: function(session) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            return lab.snapshot(function(snapshot) {
                return snapshot.sqlite.query("update slime_brand_skus set is_removed =  ? where ouid == ? ", true, session.currentOU.id)
            })
        },
        createSKU: function(session, { barcode, name, item_code, retail_unit, brand, category, list_price, market_price, image_url }) {

            if (!session.currentOU) {
                throw @lab.errors.not_login;
            }

            return lab.snapshot(function(snapshot) {
                return snapshot.slime.brand.@findSKU(session.currentOU.id, { barcode, item_code, retail_unit }).then(function(result) {
                    if (result) {
                        snapshot.slime.brand.@importSKU(session.currentOU.id, { barcode, item_code, name, retail_unit, brand, category, list_price, market_price, image_url }).pipe(this);
                    } else {
                        if (!item_code && !barcode) {

                            snapshot.slime.core.@generateNextCode(session.currentOU.id, { type: 'brand_skus' }).then(function(code) {

                                snapshot.slime.brand.@importSKU(session.currentOU.id, { item_code: code, name, retail_unit, brand, category, list_price, market_price, image_url }).pipe(this);

                            }).pipe(this);

                        } else {
                            snapshot.slime.brand.@importSKU(session.currentOU.id, { barcode, item_code, name, retail_unit, brand, category, list_price, market_price, image_url }).pipe(this);
                        }
                    }
                });
            })
        },
        /**
         * @api {jsonrpc} slime@brand.updateSKU(form)=result slime@brand.updateSKU
         * @apiDescription 更新产品数据
         * @apiGroup slime
         * @apiParam (form) {String} id 商品id
         * @apiParam (form) {String} barcode 商品条形码
         * @apiParam (form) {String} item_code 商品编码
         * @apiParam (form) {String} brand 品牌
         * @apiParam (form) {String} category 品类
         * @apiParam (form) {Number} list_price 零售价
         * @apiParam (form) {Number} market_price 原价
         * @apiParam (form) {String} image_url 图片路径
         * @apiParam (form) {String} retail_unit 零售单位
         * @apiUse TypeDefineBrand
         */
        // 更新SKU
        @updateSKU: function(currentOU, { id, barcode, item_code, retail_unit, brand, category, list_price, market_price, image_url, memo, weight, tags }) {

            return lab.snapshot(function(snapshot) {

                if (!id) {
                    throw @lab.errors.invalid_parameters;
                }

                return snapshot.find("slime_brand_skus", id).then(function(sku) {

                    if (sku) {

                        if (sku.ouid == currentOU.id) {

                            snapshot.update("slime_brand_skus", sku, { barcode, item_code, retail_unit, brand, category, list_price, market_price, image_url, memo, weight, tags, last_update: Date.now() }).then(function(updated_sku) {
                                process.nextTick(function() {
                                    @mew.auto("slime.brand.updateSKU", updated_sku);
                                });
                                this.next(updated_sku)
                            }).pipe(this);

                        } else {
                            throw @lab.errors.no_permission;
                        }

                    } else {
                        throw @lab.errors.object_not_found;
                    }
                })
            })
        },
        updateSKU: function(session, form) {

            if (!session.currentOU || !session.currentUser) {
                throw @lab.errors.not_login;
            }

            return lab.snapshot(function(snapshot) {

                if (!form.id) {
                    throw @lab.errors.invalid_parameters;
                }

                return snapshot.find("slime_brand_skus", form.id).then(function(sku) {

                    if (sku) {

                        if (sku.ouid == session.currentOU.id) {
                            let message = "";
                            let item = {
                                // "barcode": "条形码",
                                // "item_code": "商品编号",
                                "retail_unit": "规格",
                                "brand": "品牌",
                                "category": "品类",
                                "list_price": "零售价",
                                "market_price": "划线价",
                                "image_url": "商品小图",
                                "memo": "商品简介",
                                "weight": "商品重量"
                            }
                            @.keys(item).forEach(function(key) {
                                if (!@.is.nil(form[key]) && sku[key] !== form[key]) {
                                    message += `${item[key]} 从 ${sku[key]} 变更为 ${form[key]}\n`
                                    sku[key] = form[key]
                                }
                            })
                            if (message) {
                                sku.last_update = Date.now()
                                snapshot.update("slime_brand_skus", sku).then(function(updated_sku) {
                                    process.nextTick(function() {
                                        @mew.auto("slime.brand.updateSKU", updated_sku);
                                        @mew.auto("lab.add_operator_log", {
                                            currentUser: session.currentUser,
                                            target: updated_sku,
                                            target_id: updated_sku.id,
                                            method: "updateSKU",
                                            kitty: "slime.brand",
                                            type: "商品信息",
                                            message: `修改SKU商品 ${sku.item_code} ` + message
                                        })
                                    });
                                    this.next(updated_sku)
                                }).pipe(this);
                            } else {
                                this.next()
                            }

                        } else {
                            throw @lab.errors.no_permission;
                        }

                    } else {
                        throw @lab.errors.object_not_found;
                    }
                })
            })
        },
        setSKUOnSale: function(session, { id, item_code, on_sale }) {
            return @.async(function() {
                if (item_code) {
                    return lab.find("slime_brand_skus", {
                        item_code
                    })
                } else if (id) {
                    return lab.find("slime_brand_skus", id)
                } else {
                    throw @lab.errors.object_not_found;
                }
            }).then(function(result) {
                if (!result || result.is_removed) {
                    throw @lab.errors.object_not_found;
                }
                result.on_sale = !!on_sale
                result.last_update = Date.now()
                @mew.auto("slime.brand.updateSKU", result)
                @mew.auto("lab.add_operator_log", {
                    currentUser: session.currentUser,
                    target: result,
                    target_id: result.id,
                    method: "setSKUOnSale",
                    kitty: "slime.brand",
                    type: "商品信息",
                    message: `${result.on_sale ? '上架' : '下架'}SKU商品 ${result.item_code} `
                })
                return lab.update("slime_brand_skus", result)
            })
        }
    }
}